<?php
declare(strict_types=1);

namespace App\Service;

use App\Helper\Log;
use App\Helper\Util;
use Hyperf\DbConnection\Db;
use App\Service\StatisrecService;

/**
 * 公众号服务
 */
class GzhService 
{
    private $appid = "";
    private $appsecret = "";
    /**
     * [__construct description] 构造函数
     */
    public function __construct()
    {
        $wxconfig = config('wxconfig', []);
        $gzhconfig = $wxconfig['gzh']??[];
        $this->appid = $gzhconfig['appid']??NULL;
        $this->appsecret = $gzhconfig['appsecret']??NULL;
    }
    /**
     * 处理事件
     * [handleEvent description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public function handleEvent($params)
    {
        $event = $params['Event']??"";
        $openid = $params['FromUserName']??"";
        $eventKey = $params['EventKey']??"";
        switch ($event) {
            case 'subscribe':
                $this->subscribe($openid);
                $res = $this->receiveEvent($params, "subscribe");
                break;
            case 'unsubscribe':
                $this->unSubscribe($openid);
                $res = "";
                break;
            default:
                $res = "";
                break;
        }
        return $res;
    }
    /**
     * [subscribe description] 关注
     * @param  [type] $openid [description]
     * @return [type]         [description]
     */
    public function subscribe($openid)
    {
        $wx_user_info = Util::getUnionidByWxOpenid($openid, $this->appid, $this->appsecret);
        Log::get("wx_get_unionid")->info(json_encode($wx_user_info, JSON_UNESCAPED_UNICODE));
        //如果用户的unionid不存在，不再往下执行
        if(empty($wx_user_info['unionid'])){
            return false;
        }
        $staServ = new StatisrecService();
        $static_params = [
            'device'=>"wechat",
            'tag'=>'gzh_sub',
            'user_id'=>$openid,
            'save_type'=>'norepeat'
        ];
        $staServ->doSave($static_params);
        $this->subscribeLog($openid, $wx_user_info['unionid']);
    }
    /**
     * [unSubscribe description] 取消关注
     * @param  [type] $openid [description]
     * @return [type]         [description]
     */
    public function unSubscribe($openid)
    {
        $staServ = new StatisrecService();
        $static_params = [
            'device'=>"wechat",
            'tag'=>'gzh_unsub',
            'user_id'=>$openid,
            'save_type'=>'norepeat'
        ];
        $staServ->doSave($static_params);
        $this->unSubscribeLog($openid);
    }
    /**
     * 关注
     * [subscribeLog description]
     * @param  [type] $openid  [description]
     * @param  [type] $unionid [description]
     * @return [type]          [description]
     */
    public function subscribeLog($openid,$unionid)
    {
        $exists = Db::table('wxship_act')->where('openid', $openid)->first();
        //用户数据不为空，更新数据
        if (empty($exists)) {
            $insert_data = [
                'openid' => $openid,
                'unionid' => $unionid,
                'status' => 1,
                'created_at' => time(),
            ];
            Db::table('wxship_act')->insert($insert_data);
        }else{
            $update_data = [
                'unionid' => $unionid,
                'status' => 1,
                'updated_at' => time(),
            ];
            Db::table('wxship_act')->where('id', $exists['id'])->update($update_data);
        }
        //同步用户表数据
        $user_info = Db::table('user')->where('unionid', $unionid)->first();
        if (!empty($user_info) && empty($user_info['wx_openid'])) {
            $update_user = [
                'wx_openid' => $openid
            ];
            Db::table('user')->where('id', $user_info['id'])->update($update_user);
        }
    }
    /**
     * [unSubscribe description] 取消关注
     * @param  [type] $openid [description]
     * @return [type]         [description]
     */
    public function unSubscribeLog($openid)
    {
        $exists = Db::table('wxship_act')->where('openid', $openid)->first();
        //用户数据不为空，更新数据
        if (empty($exists)) {
            $insert_data = [
                'openid' => $openid,
                'status' => 0,
                'created_at' => time(),
            ];
            Db::table('wxship_act')->insert($insert_data);
        }else{
            $update_data = [
                'status' => 0,
                'updated_at' => time(),
            ];
            Db::table('wxship_act')->where('id', $exists['id'])->update($update_data);
        }
    }
    /**
     * 事件回复
     * [receiveEvent description]
     * @param  [type] $params  [description]
     * @param  [type] $keyword [description]
     * @return [type]          [description]
     */
    public function receiveEvent($params, $keyword)
    {
        $obj = Db::table('wx_keywords')->where('keywords', $keyword)->first();
        if (empty($obj)) {
            return "";
        }
        switch ($obj['type']) {
            case 'text':
                $res = $this->transmitText($params, $obj['content']);
                break;
            case 'image':
                $res = $this->transmitImage($params, $obj['content']);
                break;
            default:
                $res = "";
                break;
        }
        return $res;
    }
    /**
     * [transmitText description]
     * @param  [type] $object  [description]
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    public function transmitText($params, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $params['FromUserName'], $params['ToUserName'], time(), $content);
        return $result;
    }
    /**
     * [transmitImage 回复图片消息]
     * @param  [type] $object  [description]
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    public function transmitImage($params, $MediaId)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
    <MediaId><![CDATA[%s]]></MediaId>
  </Image>
</xml>";
        $result = sprintf($textTpl, $params['FromUserName'], $params['ToUserName'], time(), $MediaId);
        return $result;
    }
}
